package org.idea.qiyu.framework.threadpool.dynamic.executor;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 线程池监控角色
 *
 * @Author linhao
 * @Date created in 4:28 下午 2021/10/26
 */
@Configuration
@Slf4j
public class QiyuExecutorWatcher implements InitializingBean {

    @Resource
    private ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        //while循环和使用线程池
        Thread thread = new Thread(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {
                while (true) {
                    Map<String, QiyuExecutor> qiyuExecutorMap = applicationContext.getBeansOfType(QiyuExecutor.class);
                    for (String executorName : qiyuExecutorMap.keySet()) {
                        QiyuExecutor qiyuExecutor = qiyuExecutorMap.get(executorName);
                        //活跃资源得分，如果这个值比较低，那么此时线程池的资源可以进行锁容
                        double corePoolCoreActiveScore = (double) qiyuExecutor.getActiveCount() / (double) qiyuExecutor.getCorePoolSize();
                        double corePoolMaxActiveScore = (double) qiyuExecutor.getActiveCount() / (double) qiyuExecutor.getMaximumPoolSize();
                        double queueSize = qiyuExecutor.getQueueSize();
                        long taskCount = qiyuExecutor.getTaskCount();
                        long completedTaskCount = qiyuExecutor.getCompletedTaskCount();
                        log.info("【{}】，corePoolCoreActiveScore is {}, corePoolMaxActiveScore is {}, queueSize is {}, taskCount is {}, completedTaskCount is {}"
                                , executorName, corePoolCoreActiveScore, corePoolMaxActiveScore, queueSize, taskCount, completedTaskCount);
                    }
                    Thread.sleep(2000);
                }
            }
        });
        thread.start();
    }
}
